package JdbcUtils;

import com.alibaba.druid.pool.DruidDataSourceFactory;
import org.junit.Test;

import javax.sql.DataSource;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

public class JdbcUtils {
    /**
     * 使用Druid数据库连接池技术
     */
    private static DataSource dataSource;
    static {
        try {

            Properties pros=new Properties();//创建一个配置文件对象
            InputStream is = ClassLoader.getSystemClassLoader().getResourceAsStream("Druid.properties");
            pros.load(is);
            dataSource = DruidDataSourceFactory.createDataSource(pros);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static Connection getConnection() throws Exception {

        Connection connection = dataSource.getConnection();
        //System.out.println(connection);
        return connection;
    }

    /**
     * 将数据库连接返回连接池
     */
    public static void closeResource(Connection c)  {

        if (c != null) {
            try {
                c.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    }
    public static void closeResource(Connection c, Statement p, ResultSet r)  {

            if (r != null) {
                try {
                    r.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
            if (p != null) {
                try {
                    p.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
            if (c != null) {
                try {
                    c.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }

    }

}
